import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
Page({
  data: {
    // 当前的位置
    latitude: "",
    longitude: "",
    latitude1: "",
    longitude1: "",
    // 画圆
    circles: [],
    nearByList: [], // 企业后台接口信息集合
    originList: [], // 原始列表数据
    // markers: [], // 企业标记点集合
    markers: [],
    placeData: {},
    token: "",
    height: "600rpx",
    data: [],
    data1: [],
    positi: [],
    wxMarkerData: [],
    originalData: [],
    thsisab: "1",
    markerId: "",
    zb: "",
    qiyeTypeList1: [
      {
        name: "餐饮美食",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_1.svg",
        type: '0'
      },
      {
        name: "交通出行",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_2.svg",
        type: '1'
      },
      {
        name: "景点旅游",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_3.svg",
        type: '2'
      },
      {
        name: "酒店民宿",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_4.svg",
        type: '3'
      },
      {
        name: "商超百货",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_5.svg",
        type: '4'
      },
      {
        name: "生活服务",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_6.svg",
        type: '5'
      },
      {
        name: "文体娱乐",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_7.svg",
        type: '6'
      },
      {
        name: "养车用车",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_8.svg",
        type: '7'
      },
      {
        name: "医疗卫生",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_9.svg",
        type: '8'
      },
      {
        name: "其他",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/xunjian/merchant_10.svg",
        type: '9'
      },
    ],
    selectType: '',
    selectName: '',
    actionType: 1, // 默认展开
    pageNum: 1,
    total: "", // 附近企业总数
    activeTabIndex: 0, // 默认附近企业
    cyTabIndex: "",
    extraObj: {}, // 额外的查询条件
    distance: "1", // 距离
    actionTypeTest: 1,
    serach_pro: ''
  },

  serachProChange (e) {
    this.setData({
      serach_pro: e.detail,
    });
  },

  goSearch() {
    this.originInfo();
  },

  // 页面解析完成后执行
  onReady: function () {
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("merchantMap");
    this.locationBack();
  },
  onLoad: function (e) {
    const that = this;
    // 获取当前的位置信息
    getApp().globalData.getLocation({
      type: "gcj02",
      success (res) {
        // 获取当前的定位
        // that.getLocationNow(res);
        that.initInfoByCenter(res);
      },
    });
  },

  /**
   * methods
   */
  getLocationNow (info) {
    getApp()
      .globalData.request(
        "/map/inverseGeocode",
        {
          lat: this.transMarker([info.longitude, info.latitude])[1],
          lng: this.transMarker([info.longitude, info.latitude])[0],
          needToken: true
        },
        "POST"
      )
      .then((res) => {
        console.log(res);
        const rstObj = res;
        console.log();
        this.setData({
          zb: rstObj.data.replace("苏州市苏州", "苏州市"),
        });
      });
  },
  // 获取页面节点信息的方法(nodeName 节点id名称)
  getNodeInfo (nodeName) {
    const query = this.createSelectorQuery();
    query.select(`#${nodeName}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      console.log(res, "res");
      this.setData({ scrollTop: res[0].height });
    });
  },
  initInfoByCenter (res) {
    this.setData({
      longitude: res.longitude,
      latitude: res.latitude,
      // longitude: this.transMarker([res.longitude, res.latitude])[0],
      // latitude: this.transMarker([res.latitude, res.latitude])[1],
      longitude1: res.longitude,
      latitude1: res.latitude,
    });
    this.setData({
      circles: [
        {
          latitude: res.latitude,
          longitude: res.longitude,
          color: "#7cb5ec88",
          opacity: 0.2,
          fillColor: "#7cb5ec88",
          radius: 600,
          strokeWidth: 2,
        },
      ],
    });

    // 数据初始化
    this.initInfos();
  },
  // 初始化数据
  async initInfos () {
    // 获取周边企业的坐标
    await this.getNearByInfos();
    // 初始化markers
    this.initMarkers();
  },


  cellCheckToggle(e) {
    // console.log(e.currentTarget.dataset, 'e')
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.setData({ // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
      merchantName: e.currentTarget.dataset.name
    })
    wx.navigateBack({
      delta: 1 // 返回上一级页面。
    })
  },

  // 获取附近企业的坐标
  async getNearByInfos () {
    const params = {
      distance: this.data.distance,
      userLng: this.data.longitude,
      userLat: this.data.latitude,
      // userLng: 120.68151,
      // userLat: 31.322478,
      // pageBO: {
      pageSize: 50,
      pageNum: this.data.pageNum,
      // },
      name: this.data.serach_pro,
      needToken: true,
      labelType: this.data.selectName
    };
    wx.showLoading({
      title: "加载中",
    });
    console.log({ ...params, ...this.data.extraObj }, "附近企业查询条件");
    const { list, total } = await getApp().globalData.request(
      "/map/lookAddress",
      { ...params, ...this.data.extraObj },
      "POST"
    );
    setTimeout(function () {
      wx.hideLoading();
    }, 800);
    console.log(list);
    // 原始列表数据
    this.setData({
      originList: this.data.originList.concat(list),
      total: total,
    });
    // 处理数据
    const resInfos = this.findSameList(this.data.originList);
    this.setData({
      nearByList: resInfos,
    });
    // console.log(this.data.originList, "原始附近企业查询结果");
    // console.log(this.data.nearByList, "附近企业查询结果");
  },

  // 初始化点标记
  initMarkers () {
    const markers = [];
    this.data.nearByList.forEach((val, index) => {
      // const zuobiao = this.transMarker1([val[0].longitude, val[0].latitude]);
      const longitude = val[0].longitude;
      const latitude = val[0].latitude;
      // const longitude = zuobiao[0];
      // const latitude = zuobiao[1];
      markers.push({
        id: index,
        latitude: latitude,
        longitude: longitude,
        name: val[0].name,
        // corpKey: val[0].corpKey,
        iconPath:
          "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png",
        desc: "我现在的位置",
        title: val[0].name,
        width: 14,
        height: 21,
        callout: {
          content: `${val[0].name}${val.length > 0 ? "等" + val.length + "商户 " : ""
            }`,
          color: "#ffffff",
          bgColor: "#505d58", //需要6位的色值有效
          fontSize: 14,
          borderRadius: 2,
          padding: 5,
          display: "BYCLICK", //'BYCLICK':点击显示; 'ALWAYS':常显
        },
      });
    });
    // 中心点自定义样式
    // markers.push({
    //   id: 9999,
    //   latitude: this.data.circles[0].latitude,
    //   longitude: this.data.circles[0].longitude,
    //   name: "",
    //   iconPath:
    //     " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/center-location2.png",
    //   desc: "我现在的位置",
    //   title: "",
    //   width: 23,
    //   height: 31,
    // });
    this.setData({
      markers: markers,
    });
    // console.log(markers, "markers");
  },

  // 打开模糊地址搜索
  openSearch () {
    const that = this;
    wx.chooseLocation({
      success (res) {
        // that.setData({
          // zb: JSON.stringify({
          //   longitude: res.longitude,
          //   latitude: res.latitude,
          // }),
        // });
        console.log(res, "返回的结果");
        // 重新定位中心点，分页参数重置，原markers清除
        that.setData({
          pageNum: 1,
          originList: [],
        });
        that.initInfoByCenter(res);
        // that.initInfoByCenter({ longitude: 120.642391, latitude: 31.369189 });
        console.log(res, "成功回调");
      },
      fail (res) {
        console.log(res, "失败回调");
      },
      complete (res) {
        console.log(res, "结束回调");
      },
    });
  },

  // 坐标系转化
  transMarker (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },

  // 中心点坐标转化
  transMarker1 (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },

  // 查找重复的数据,并且重新排列
  findSameList (item) {
    const needList = JSON.parse(JSON.stringify(item));
    // console.log(needList, 'needList')
    // 先去重复
    const singleList = this.removeDuplicateObj(needList);
    // console.log(singleList, 'singleList')
    const showList = [];
    singleList.forEach((val, index) => {
      const itemList = [];
      needList.forEach((pre) => {
        if (val.latitude === pre.latitude) {
          itemList.push(pre);
        }
      });
      showList.push(itemList);
    });
    // console.log(showList, "showList");
    return showList;
  },

  removeDuplicateObj (arr) {
    let obj1 = {};
    let obj2 = {};
    let arr1 = [];
    let arr2 = [];
    arr1 = arr.reduce((newArr, next) => {
      obj1[next.latitude] ? "" : (obj1[next.latitude] = 1 && newArr.push(next));
      return newArr;
    }, []);
    // console.log(arr1, "arr1");
    arr2 = arr1.reduce((newArr, next) => {
      obj2[next.longitude]
        ? ""
        : (obj2[next.longitude] = 1 && newArr.push(next));
      return newArr;
    }, []);
    return arr2;
  },

  // 跳转企业详情或者企业列表
  markerCalloutTap (e) {
    // console.log(e.markerId, "e");
    // if (this.data.nearByList[e.markerId].length > 1) {
    //   // 跳转到列表页面
    //   wx.navigateTo({
    //     url: `../../packageB/pages/businesses/businesses?businesses=${JSON.stringify(
    //       this.data.nearByList[e.markerId]
    //     )}`,
    //   });
    // } else {
    //   // 跳转到详情页面
    //   wx.navigateTo({
    //     url: `/pages/mapDetail/mapDetail?corpKey=${this.data.nearByList[e.markerId][0].corpKey
    //       }&latitude=${this.data.nearByList[e.markerId][0].latitude}&longitude=${this.data.nearByList[e.markerId][0].longitude
    //       }&distance=${this.data.nearByList[e.markerId][0].distance}`,
    //   });
    // }
  },

  // 扩展
  open () {
    this.setData({
      actionType: 1,
    });
    this.getNodeInfo("sticky1");
    setTimeout(() => {
      this.setData({
        actionTypeTest: 1,
      });
    }, 500);
  },

  // 收缩
  close () {
    this.setData({
      actionType: 0,
      actionTypeTest: 0,
    });
  },

  toprodetail (e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${e.detail.distance}`,
    });
  },
  // 滑动底部加载更多
  scrollBottom () {
    if(this.data.originList.length < this.data.total) {
      this.setData({
        pageNum: ++this.data.pageNum,
      });
      this.initInfos();
    }
  },

  location (e) {
    wx.openLocation({
      latitude: e.currentTarget.dataset.lat,
      longitude: e.currentTarget.dataset.lng,
      name: e.currentTarget.dataset.name,
      address: e.currentTarget.dataset.address,
      scale: 18,
    });
  },
  // 切换分类
  clickCy1 (e) {
    const type = e.currentTarget.dataset.type
    const name = e.currentTarget.dataset.name
    this.setData({
      selectType: type == this.data.selectType ? '' : type,
      selectName: name == this.data.selectName ? '' : name
    })
    this.originInfo()
  },
  clickCy2 (e) {
    // console.log(e, "e");
    wx.navigateTo({
      url: `../qiye/qiye?titleName=${this.data.qiyeAllList2[e.currentTarget.dataset.index]
        }`,
    });
  },

  // 返回到当前定位视窗
  locationBack () {
    this.mapCtx.moveToLocation();
  },

  tabTuijian (e) {
    this.setData({
      extraObj: {},
    });
    switch (e.detail.title) {
      case "附近500m企业":
        const params0 = {
          distance: 0.5,
        };
        this.setData({
          extraObj: params0,
        });
        this.originInfo();
        break;
      case "营收500万-1000万":
        const params1 = {
          businessIncomeLowerLimit: "500",
          businessIncomeUpperLimit: "1000",
        };
        this.setData({
          extraObj: params1,
        });
        this.originInfo();
        break;
      case "营收1000万以上":
        const params2 = {
          businessIncomeLowerLimit: "1000",
          businessIncomeUpperLimit: "50000",
        };
        this.setData({
          extraObj: params2,
        });
        this.originInfo();
        break;
      case "有融资需求企业":
        const params3 = {
          isLoan: "1",
        };
        this.setData({
          extraObj: params3,
        });
        this.originInfo();
        break;
      case "未结清信贷企业":
        const params4 = {
          qutstandingLoans: "1",
        };
        this.setData({
          extraObj: params4,
        });
        this.originInfo();
        break;
      case "未结清小额贷款企业":
        const params5 = {
          qutstandingSmallLoans: "1",
        };
        this.setData({
          extraObj: params5,
        });
        this.originInfo();
        break;
      case "纳税A级企业":
        const params6 = {
          taxALeavel: "1",
        };
        this.setData({
          extraObj: params6,
        });
        this.originInfo();
        break;
      case "用水企业":
        const params7 = {
          isWater: "1",
        };
        this.setData({
          extraObj: params7,
        });
        this.originInfo();
        break;
      case "用电企业":
        const params8 = {
          isElec: "1",
        };
        this.setData({
          extraObj: params8,
        });
        this.originInfo();
        break;
      case "缴纳社保企业":
        const params9 = {
          isSecurity: "1",
        };
        this.setData({
          extraObj: params9,
        });
        this.originInfo();
        break;
      case "缴纳公积金企业":
        const params10 = {
          isFund: "1",
        };
        this.setData({
          extraObj: params10,
        });
        this.originInfo();
        break;
      case "附近1km企业":
        const params11 = {
          distance: 1.0,
        };
        this.setData({
          extraObj: params11,
        });
        this.originInfo();
        break;
      case "外贸进口增长":
        const params12 = {
          importTrend: '1',
        };
        this.setData({
          extraObj: params12,
        });
        this.originInfo();
        break;
      case "外贸出口增长":
        const params13 = {
          exportTrend: '1',
        };
        this.setData({
          extraObj: params13,
        });
        this.originInfo();
        break;
      case "资产负债率50%-100%":
        const params14 = {
          debtLowerLimit: '50',
          debtUpperLimit: '100',
        };
        this.setData({
          extraObj: params14,
        });
        this.originInfo();
        break;
      case "专利发明增加":
        const params15 = {
          patentTrend: '1',
        };
        this.setData({
          extraObj: params15,
        });
        this.originInfo();
        break;
      case "国有银行有贷":
        const params16 = {
          loanStateBank: '1',
        };
        this.setData({
          extraObj: params16,
        });
        this.originInfo();
        break;
      case "有小额贷款":
        const params17 = {
          smallLoan: '1',
        };
        this.setData({
          extraObj: params17,
        });
        this.originInfo();
        break;
      default:
        break;
    }
  },

  tabTuijianCy (e) {
    const params = {
      keyIndustries:
        e.detail.title === "重点产业" ? "" : e.detail.title + "产业",
    };
    this.setData({
      extraObj: params,
    });
    this.originInfo();
  },

  // 初始化
  originInfo () {
    this.setData({
      pageNum: 1,
      originList: [],
    });
    this.initInfos();
  },
});
